package com.atguigu.mapreduce.solution;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.*;

public class SolutionReducer2 extends Reducer<Text, Text, Text, Text> {
    private final Text result = new Text();
    private final StringBuilder sb = new StringBuilder();

    private final List<String> tempResult = new ArrayList<>();

    @Override
    protected void reduce(Text key, Iterable<Text> values, Reducer<Text, Text, Text, Text>.Context context) throws IOException, InterruptedException {
        tempResult.clear();
        for (Text value : values) {
            tempResult.add(value.toString());
        }
        tempResult.sort((str1, str2) -> {
            String[] str1Fields = str1.split(":");
            String[] str2Fields = str2.split(":");
            int compare = Integer.compare(Integer.parseInt(str2Fields[1]), Integer.parseInt(str1Fields[1]));
            return compare != 0 ? compare : str1Fields[0].compareTo(str2Fields[0]);
        });
        sb.setLength(0);
        sb.append(tempResult.get(0));
        for (int i = 1; i < tempResult.size(); i++) {
            sb.append(",").append(tempResult.get(i));
        }
        result.set(sb.toString());
        context.write(key, this.result);
    }
}
